package org.easy.excel.support;

import org.easy.excel.support.config.ExcelConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.tool.TipException;
import org.tool.io.file.FileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 系统文件-Excel导出服务
 *
 * @author 李坤
 * @date 2022/4/27 15:01
 */
@Service
public class FileExcelExportService implements ExcelExportService {

    private final Logger logger = LoggerFactory.getLogger(FileExcelExportService.class);

    /**
     * 通过 HttpServletResponse 导出Excel
     *
     * @param path        文件导出路径
     * @param dataList    数据
     * @param excelConfig 导出配置
     */
    public void export4ServletResponse(String path, List<?> dataList, ExcelConfig excelConfig) {
        final File file;
        try {
            path = path.endsWith("\\") ? path : path + "\\";
            file = FileUtil.getFile(path + excelConfig.getFileName() + ".xlsx");
        } catch (IOException exception) {
            throw new TipException(String.format("获取文件路径 %s 失败", path));
        }

        try {
            export(new FileOutputStream(file), excelConfig);
        } catch (IOException exception) {
            throw new TipException(String.format("导出数据 %s 失败；原因：%s", dataList, exception.getMessage()));
        }
    }

}
